package com.hejl.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;

/**
 * @author Hejl
 * @version 1.0
 * @description
 * @className OtherController
 * @date 2025/6/11 2:39
 */
@RestController
public class ImageModelController {
    @Autowired
    private DashScopeImageModel imageModel;

    /**
     * @description: 根据输入生成图片
     * @param: [msg, response]
     * @return: void
     * @author: Hejl
     * @date: 2025/6/11 2:41
     */
    @GetMapping("/image")
    public void getImage(@RequestParam(value = "msg", defaultValue = "生成一只狸花猫") String msg, HttpServletResponse response) {
        ImageResponse imageResponse = imageModel.call(new ImagePrompt(msg, DashScopeImageOptions.builder()
                .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)//模型
                .withN(1)//生成图片数量
                .withHeight(1024)//图片高度
                .withWidth(1024)//图片宽度
                .build()));
        //获取生成图像的地址
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        //在浏览器输出
        try {
            //使用输出流在浏览器输出
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(in.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
        }

    }
}